package com.android.awacs.wifi;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import android.content.Context;
import android.content.Intent;

import com.android.awacs.R;
import com.android.awacs.gps.GoogleMap;
import com.android.awacs.util.StringParser;

/*
 * Service lance par le menu qui affiche la liste des options WiFi
 * Equivalent (modifié) du SmsMessagemenu
 */
public class WiFiMessageScanMenu extends Activity {

	// Protocole de communication avec les boards Arduino
	private final String SEND_ME_GPS = "#1";
	private final String SEND_ME_THM = "#2";
	private final String SEND_ME_DOO = "#3";
	private final String SEND_ME_LUM = "#4";

	public final String TAG_GPS = "GPS"; // reception de coordonnees GPS
	public final String TAG_THM = "THM"; // reception de donnees thermiques
	public final String TAG_DOO = "DOO"; // reception de porte ouverte ou non
	public final String TAG_LUM = "LUM"; // reception de la luminosite

	public static Socket SOCKET;
	public static Context context;
	public final static int SERVER_PORT = 1919;

	private Spinner m_myDynamicSpinner;
	private ArrayAdapter<CharSequence> m_adapterForSpinner;	

	private ArrayList<WiFiModule> modules = null;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = getApplicationContext();

		// Afficher la GUI principale
		setContentView(R.layout.wifi_msg_scan_menu);

		Button btnScan = (Button) findViewById(R.id.wifi_scan);
		m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);        

		// Creation et ecoute des quatre boutons
		final Button btnGPS = (Button) findViewById(R.id.envoyer_gps);
		final Button btnTHM = (Button) findViewById(R.id.envoyer_thm);
		final Button btnDOO = (Button) findViewById(R.id.envoyer_doo);
		final Button btnLUM = (Button) findViewById(R.id.envoyer_lum);

		final EditText numero = (EditText) findViewById(R.id.numero);

		m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
		m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);        
		m_myDynamicSpinner.setAdapter(m_adapterForSpinner);

		btnScan.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				try {

					m_adapterForSpinner.clear();

					//On donne le reseau à scanner
					WiFiScanIP scan = new  WiFiScanIP("192.168.0.");

					//Ca nous retourne une liste d'ip qui sont up (pingable)
					ArrayList<String> ips = scan.getReachable();
					System.out.println("Liste des ip reachable : "+ips);  

					//On crée un scanModule
					WiFiScanModule scanModules = new WiFiScanModule();

					/* Et on lance le scan avec la liste d'ips up du dessus.
					 * Ca retourne une liste de module
					 * Chaque module étant une ip et une liste de ses services
					 */
					try {
						modules = scanModules.scanStart(ips);
					} catch (InterruptedException e) {e.printStackTrace();}

					for(WiFiModule m: modules)
						m_adapterForSpinner.add(m.toString());

					//Ce code est utilisable avec des modules arduino qui comportent le bon protocole
				} catch (Exception e) {}
			}
		});

		// Rend visible et invisible les boutons selon les modules dispo sur la machine selectionnee
		m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent,
					View view, int pos, long id) {
				String functions = parent.getItemAtPosition(pos).toString();

				if(functions.contains(TAG_GPS) == true)
					btnGPS.setVisibility(View.VISIBLE);
				else 
					btnGPS.setVisibility(View.INVISIBLE);

				if(functions.contains(TAG_THM) == true)
					btnTHM.setVisibility(View.VISIBLE);
				else 
					btnTHM.setVisibility(View.INVISIBLE);

				if(functions.contains(TAG_LUM) == true)
					btnLUM.setVisibility(View.VISIBLE);
				else 
					btnLUM.setVisibility(View.INVISIBLE);

				if(functions.contains(TAG_DOO) == true)
					btnDOO.setVisibility(View.VISIBLE);
				else 
					btnDOO.setVisibility(View.INVISIBLE);	
			}
			public void onNothingSelected(AdapterView parent) {	}
		});	

		// Code similaire pour chaque bouton, on envoie juste un message collant au protocole
		btnGPS.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				String ip = "localhost";
				String num = m_myDynamicSpinner.getSelectedItem().toString();

				for(WiFiModule m: modules)
					if(m.toString().compareTo(num)==0){
						ip=m.getIP();
						break;
					}

				try {
					Socket s = new Socket(ip, SERVER_PORT);
					Intent i = new Intent(context, GoogleMap.class);
					Bundle b = new Bundle();
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
					BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
					writer.write("#1\n");
					writer.flush();
					String ligne;
					ligne = reader.readLine();
					// Toast.makeText(context, ligne, Toast.LENGTH_LONG).show();
					String[] tokens = ligne.split(" ");
					if (tokens[0].compareToIgnoreCase(TAG_GPS)==0){
						String contenu = ligne.substring(4, ligne.length());
						StringParser parse = new StringParser();
						parse.GPS(contenu, b);
					}
					writer.close();
					reader.close();
					s.close();
					i.putExtras(b);
					i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					context.startActivity(i);
				} catch (Exception e) {}
			}
		});

		// Code similaire pour chaque bouton, on envoie juste un message collant au protocole
		btnTHM.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				String ip = "localhost";
				String num = m_myDynamicSpinner.getSelectedItem().toString();

				for(WiFiModule m: modules)
					if(m.toString().compareTo(num)==0){
						ip=m.getIP();
						break;
					}

				try {
					Socket s = new Socket(ip, SERVER_PORT);
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
					BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
					writer.write("#2\n");
					writer.flush();
					String ligne;
					ligne = reader.readLine();
					String[] tokens = ligne.split(" ");
					if (tokens[0].compareToIgnoreCase(TAG_THM)==0)
						Toast.makeText(context, "Température : " + tokens[1] + "°C", Toast.LENGTH_LONG).show();
					writer.close();
					reader.close();
					s.close();
				} catch (Exception e) {}
			}
		});

		// Code similaire pour chaque bouton, on envoie juste un message collant au protocole
		btnDOO.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				String ip = "localhost";
				String num = m_myDynamicSpinner.getSelectedItem().toString();

				for(WiFiModule m: modules)
					if(m.toString().compareTo(num)==0){
						ip=m.getIP();
						break;
					}

				try {
					Socket s = new Socket(ip, SERVER_PORT);
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
					BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
					writer.write("#3\n");
					writer.flush();
					String ligne;
					ligne = reader.readLine();
					String[] tokens = ligne.split(" ");
					if (tokens[0].compareToIgnoreCase(TAG_DOO)==0)
						Toast.makeText(context, "Etat de la porte : " + tokens[1], Toast.LENGTH_LONG).show();
					writer.close();
					reader.close();
					s.close();
				} catch (Exception e) {}
			}
		});

		// Code similaire pour chaque bouton, on envoie juste un message collant au protocole
		btnLUM.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				String ip = "localhost";
				String num = m_myDynamicSpinner.getSelectedItem().toString();

				for(WiFiModule m: modules)
					if(m.toString().compareTo(num)==0){
						ip=m.getIP();
						break;
					}

				try {
					Socket s = new Socket(ip, SERVER_PORT);
					BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
					BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
					writer.write("#4\n");
					writer.flush();
					String ligne;
					ligne = reader.readLine();
					String[] tokens = ligne.split(" ");
					if (tokens[0].compareToIgnoreCase(TAG_LUM)==0)
						Toast.makeText(context, "Luminosité :" + tokens[1] + "%", Toast.LENGTH_LONG).show();
					writer.close();
					reader.close();
					s.close();
				} catch (Exception e) {}
			}
		});
	}
}